package com.archway.appframe.frame.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class RandomNumMaker {

	private static Color getRandomColor(int x) {
		Color coler = null;
		switch(x){
			case 0: coler=Color.pink; 
			case 1: coler=Color.black; 
			case 2: coler=Color.blue; 
			case 3: coler=Color.gray; 
			case 4: coler=Color.green; 
			case 5: coler=Color.black; 
			case 6: coler=Color.orange; 
		}
		return coler;
	}
	
	
	public static boolean getRandomNumPic( String randomNum,OutputStream io) throws Exception {
		// 在内存中创建图象
		int iWidth = 60, iHeight = 23;
		BufferedImage image = new BufferedImage(iWidth, iHeight,
				BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		Graphics g = image.getGraphics();
		// 设定背景色
		g.setColor(Color.white);
		g.fillRect(0, 0, iWidth, iHeight);
		// 画边框
		//g.setColor(Color.GRAY);
		//g.drawRect(0, 0, iWidth - 1, iHeight - 1);
		// 取随机产生的认证码(4位数字)
		String rand = randomNum;
//		rand = rand.substring(0, rand.indexOf("."));
//		switch (rand.length()) {
//		case 1:
//			rand = "000" + rand;
//			break;
//		case 2:
//			rand = "00" + rand;
//			break;
//		case 3:
//			rand = "0" + rand;
//			break;
//		default:
//			rand = rand.substring(0, 4);
//			break;
//		}
		// 将认证码存入SESSION
		//session.setAttribute("Rand", rand);
		// 将认证码显示到图象中
		g.setColor(Color.blue);
		//Segoe Print
		//Times New Roman
		g.setFont(new Font("Segoe Print", Font.ITALIC, 16));
		g.drawString(rand, 5, 15);
		// 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到
		Random random = new Random();
		for (int iIndex = 0; iIndex < 58; iIndex++) {
			int x = random.nextInt(iWidth);
			int y = random.nextInt(iHeight);
			g.setColor(getRandomColor(iIndex%6));
			if(iIndex%4==1)
				g.drawLine(x, y, x, y);
			if(iIndex%23==1)
				g.drawLine(x, y, 58-x, 58-y);
		}
		// 图象生效
		g.dispose();
		//out.clear();
		//out = pageContext.pushBody();
		// 输出图象到页面
		return ImageIO.write(image, "JPEG", io);
	}
	
	
	public static void main(String[] args) throws Exception {
		RandomNumMaker maker =  new RandomNumMaker();
		File file2 = new File("h:\\1.JPEG");
		OutputStream out = new FileOutputStream(file2);
		maker.getRandomNumPic("AB34", out);
	}
	
	
}
